<?php
/**
 * Description:微信access_token相关
 * User: wh
 * Date: 2017-07-25
 * Time: 10:22
 */
namespace app\wxbackend\controller\Wx;
use Cache\Redis;

class WxAccessToken {

    public static function getAccessToken()
    {
        $accessToken = self::checkAccessToken();
        if (!$accessToken) {
            $accessToken = self::catchAccessToken();
        }
        return $accessToken;
    }

    //从微信公众平台得到access_token
    public static function catchAccessToken()
    {
        $urlAccessToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APPID."&secret=".APPSECRET;
        $accessToken = Curl::callWebServer($urlAccessToken, '', 'GET');
        if(!isset($accessToken['access_token'])){
            zft_log('wx/access_token', "获取access_token失败，信息:".json_encode($accessToken).'APPSECRET='. APPSECRET,'APPID=',APPID);
            exit('获取access_token失败');
        }
        //设置redis
        $key = 'ACCESS_TOKEN'.APPID;
        self::getRedis()->set($key, $accessToken['access_token'], $accessToken['expires_in']);
        return $accessToken['access_token'];
    }

    //检查是否已有access_token
    public static function checkAccessToken()
    {
        $key = 'ACCESS_TOKEN'.APPID;
        $accessToken = self::getRedis()->get($key);
        return $accessToken ?: false;
    }

    //获取redis对象
    public static function getRedis()
    {
        static $redis;
        if (!$redis) {
            $redis = new Redis();
        }
        return $redis;
    }
}